<?php
namespace App\Helper;

use QL\QueryList;
use GuzzleHttp\Client;
/**
* 采集具体新闻内容

**/
class CollectNewsContent
{
	protected $info;
	public function __construct($info = '')
    {

		$this->info = $info;
		if(!$info->option || !$info->option->content_options || !is_array($info->option->content_options))
		{
			return false;
		}
		
    }
	public function collectNews()
	{
		$info = $this->info;
		$ruls = [];
		// dd($info->option->content_options);
		$cont = [];
		foreach($info->option->content_options as $key=>$row)
		{
			if($key == 'content')
			{
				$ruls[$key] = [$row, 'html'];
				$cont[$key] = [$row, 'html'];
				break;
			}else{
				$f = 'text';
				if($key == 'page_link')
				{
					$f = 'href';
				}
				$ruls[$key] = [$row, $f];
			}
		}
		$client = new Client();
		$res = $client->request('GET', $this->do_url($info->option, $info->url));
		if($res->getStatusCode()!=200)return false;
		$body = $res->getBody()->getContents();
		$html = $this->change_encoding($body);
		
		$data = QueryList::html($html)->rules($ruls)->query()->getData();
		if($data->isEmpty())
		{
			return false;
		}
		
		$news = $data->first();
		//判断字符集
		foreach($news as $key=>$row)
		{
			$news[$key] = $this->change_encoding($row);
		}
		// dd($data);
		//获取分页内容
		if($data->count()>0 && $news['page_link'])
		{
			unset($ruls['page_link']);
			foreach($data as $k=>$row)
			{

				$temp = QueryList::get($this->do_url($info->option , $row['page_link']))->rules($cont)->query()->getData();
				if(!$temp->isEmpty())
				{
					$c = $temp->first();
					if($c)$news['content'] .= $this->change_encoding($c['content']);
				}
				
			}
			
		}
		//去除分页
		$news['content'] = $this->filter_html($news['content'],$info->option->content_options['page']);
		// dd($news);
		// $content = QueryList::html($news['content'])->find($info->option->content_options['page'])->remove();
		return $news;
	}
	public function filter_html($content, $filter)
	{
		$ql = QueryList::html($content);
		//处理图片链接
		$ql->find('img')->map(function($img){
		    $src = $this->do_url($this->info->option, $img->attr('src'));
		    // dd($src);
		    $img->replaceWith('<img src="'.$src.'" />');
		});
		//过滤分页
        $ql->find($filter)->remove();
        return $ql->find('')->html();
	}
	public function do_url($row = '', $url)
	{
		if(strstr($url, 'http'))
		{
			return $url;
		}
		return $row->host.$url;
	}
	public function change_encoding($text)
	{
		$text = str_replace(['gb2312', 'GB2312', 'GBK', 'gbk'], 'utf-8', $text);
		$e = mb_detect_encoding($text, array('UTF-8', 'gb2312'));
		
		if($e !='UTF-8')
		{
			return iconv($e,'UTF-8//IGNORE',$text);
		}else{
			return $text;
		}
		
		
	}
}